/*
 * $Id: NotifyTask.java,v 1.10 2009/11/09 18:45:34 navdeep_mahajan Exp $
 * 
 * Copyright (C) 2008 General Electric Company. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 * 
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
package com.ge.healthcare.autosc.processor.dispatcher.tasks;

import javax.mail.MessagingException;

import org.springframework.util.Assert;

import com.ge.healthcare.autosc.common.ASCLogger;
import com.ge.healthcare.autosc.common.ASCUtil;
import com.ge.healthcare.autosc.common.database.dao.IRequestDAO;
import com.ge.healthcare.autosc.common.database.dao.IRequestPropertiesDAO;
import com.ge.healthcare.autosc.common.database.pojo.ActRequest;
import com.ge.healthcare.autosc.common.database.pojo.ActRequestProperties;
import com.ge.healthcare.autosc.common.database.pojo.ActTask;
import com.ge.healthcare.autosc.common.dbLogger.StepLogger;
import com.ge.healthcare.autosc.common.exceptions.PropertyException;
import com.ge.healthcare.autosc.common.util.mail.MailInfo;
import com.ge.healthcare.autosc.common.util.mail.SendMail;
import com.ge.healthcare.autosc.common.util.mail.support.MailGenerator;
import com.ge.healthcare.autosc.processor.PrcCodeConstants;
import com.ge.healthcare.autosc.processor.exception.TaskException;

/**
 * 
 * @author 212042946
 * 
 */
public class NotifyTask extends BasicTask {

	private static IRequestDAO iRequestDAO = null;
	private static IRequestPropertiesDAO rqPropertiesDAO = null;
	private static MailGenerator mailGenerator = null;
	public static final String MSG_SUPPRESSED = " Message Suppressed at User Request ";
	public static final String MSG_SENT = "Sending E-mail";

	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		String defaultMsg = "object is required.";
		Assert.notNull(iRequestDAO, "ActRequestDAO " + defaultMsg);
		Assert.notNull(rqPropertiesDAO, "rqPropertiesDAO " + defaultMsg);
		Assert.notNull(mailGenerator, "MailTextGenerator " + defaultMsg);
	}
	/**
	 * This is the method actually run by the application during processing.
	 */
	public void executeTask(ActTask task) throws TaskException {
		run(task);
	}
	/**
	 * The run method is the actual execution that allows a return value for testing
	 * @param task
	 * @return
	 * @throws TaskException
	 */
	public StringBuffer run(ActTask task) throws TaskException {
		StringBuffer log = new StringBuffer("Prepare to send notification");
		log.append(" for task id: ").append(task.getTaskId());

		ActRequest request = getRequest(task);
		if (isEmailSuppressed(request)) {
			log.append(MSG_SUPPRESSED);
		} else {
			MailInfo mailInfo = null;
			try {
				mailInfo = mailGenerator.generate(request, task);
				if (!ASCUtil.isNullOrEmptyObject(mailInfo)) {
					log.append(MSG_SENT);
					SendMail.createNotify(mailInfo);
				} else {
					log.append("Msg was not created");
				}
			} catch (TaskException te) {
				log.append("Failed constructing email");
				log.append(" Exception: ").append(te.getMessage());
				throw new TaskException(te.getMessage(), te,
						PrcCodeConstants.PRC_F_APP_002);
			} catch (PropertyException pe) {
				StringBuffer msg = new StringBuffer();
				msg.append("Unable to read property from property file. ");
				msg.append("Exception: ").append(pe.getMessage());
				log.append(msg);
				ASCLogger.info(this.getClass(), "executeTask", msg.toString(), pe);
				throw new TaskException(msg.toString(), pe,
						PrcCodeConstants.PRC_F_APP_002);
			} catch (MessagingException me) {
				log.append("Failed sending mail: ");
				log.append(me.getMessage());

				StringBuffer msg = new StringBuffer().append(
						"Failed sending email. Mail Information:\n").append(
						mailInfo).append("\nException: ").append(
						me.getMessage());
				ASCLogger.info(this.getClass(), "executeTask", msg.toString(), me);
				throw new TaskException(msg.toString(), me,
						PrcCodeConstants.PRC_F_APP_002);
			} finally {
				StepLogger.addStepLog(log.toString());
			}
		}
		return log;
	}

	private ActRequest getRequest(ActTask task) {
		ActRequest request = null;
		request = (ActRequest) iRequestDAO.getByRequestID(task.getRequestId());
		if (ASCUtil.isNullOrEmptyObject(request)) {
			StringBuffer msg = new StringBuffer();
			msg.append("Request not found for Task id: ");
			msg.append(task.getTaskId());
			msg.append(" request Id: ").append(task.getRequestId());
			ASCLogger.error(this.getClass(), "getRequest", msg.toString());
			StepLogger.addStepLog(msg.toString());
			throw new TaskException(msg.toString(),
					PrcCodeConstants.PRC_F_APP_002);
		}
		return request;
	}

	private boolean isEmailSuppressed(ActRequest request) {
		boolean isSuppressed = false;
		ActRequestProperties noEmail = rqPropertiesDAO
				.getRequestPropertiesByRequestIdAndName(request.getRequestId(),
						ActRequestProperties.NO_MAIL);
		if (!ASCUtil.isNullOrEmptyObject(noEmail)) {
			isSuppressed = true;
		}
		return isSuppressed;
	}

	/**
	 * @param requestDAO
	 *            the iRequestDAO to set
	 */
	public void setIRequestDAO(IRequestDAO requestDAO) {
		NotifyTask.iRequestDAO = requestDAO;
	}

	/**
	 * @param rqPropertiesDAO
	 *            the rqPropertiesDAO to set
	 */
	public void setRqPropertiesDAO(IRequestPropertiesDAO rqPropertiesDAO) {
		NotifyTask.rqPropertiesDAO = rqPropertiesDAO;
	}

	/**
	 * @param mailGenerator
	 *            the mailGenerator to set
	 */
	public void setMailGenerator(MailGenerator mailGenerator) {
		NotifyTask.mailGenerator = mailGenerator;
	}
}
